package com.example.mplayer

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.annotation.OptIn
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Icon
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.media3.common.util.UnstableApi
import androidx.activity.OnBackPressedCallback
import androidx.activity.compose.LocalOnBackPressedDispatcherOwner
import androidx.compose.runtime.DisposableEffect
import com.example.mplayer.data.Video
import com.example.mplayer.screens.CardManagementScreen
import com.example.mplayer.screens.CourseDetailScreen
import com.example.mplayer.screens.CoursesScreen
import com.example.mplayer.screens.SettingsScreen
import com.example.mplayer.screens.VideoPlayerScreen
import com.example.mplayer.ui.theme.MplayerTheme
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideInHorizontally
import androidx.compose.animation.slideOutHorizontally
import androidx.compose.animation.togetherWith

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            MplayerTheme {
                MainScreen()
            }
        }
    }
}

@OptIn(UnstableApi::class)
@Composable
fun MainScreen() {
    var selectedTab by remember { mutableIntStateOf(0) }
    var currentSettingsScreen by remember { mutableStateOf<String?>(null) }
    var currentCourseId by rememberSaveable { mutableStateOf<String?>(null) }
    var currentVideo by rememberSaveable { mutableStateOf<Video?>(null) }
    
    var isNavigatingForward by remember { mutableStateOf(true) }
    
    val backDispatcher = LocalOnBackPressedDispatcherOwner.current?.onBackPressedDispatcher
    DisposableEffect(backDispatcher) {
        val callback = object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                isNavigatingForward = false
                when {
                    currentVideo != null -> {
                        currentVideo = null
                    }
                    currentCourseId != null -> {
                        currentCourseId = null
                    }
                    currentSettingsScreen != null -> {
                        currentSettingsScreen = null
                    }
                    selectedTab != 0 -> {
                        selectedTab = 0
                    }
                    else -> {
                        isEnabled = false
                        backDispatcher?.onBackPressed()
                    }
                }
            }
        }
        backDispatcher?.addCallback(callback)
        onDispose {
            callback.remove()
        }
    }
    
    Scaffold(
        modifier = Modifier.fillMaxSize(),
        bottomBar = {
            if (currentCourseId == null && currentVideo == null && currentSettingsScreen == null) {
                NavigationBar {
                    NavigationBarItem(
                        selected = selectedTab == 0,
                        onClick = { 
                            selectedTab = 0
                            currentSettingsScreen = null 
                        },
                        icon = { Icon(painter = painterResource(id = R.drawable.ic_courses), contentDescription = "Courses") },
                        label = { Text("课程") }
                    )
                    NavigationBarItem(
                        selected = selectedTab == 1,
                        onClick = { 
                            selectedTab = 1
                            currentSettingsScreen = null 
                        },
                        icon = { Icon(painter = painterResource(id = R.drawable.ic_settings), contentDescription = "Settings") },
                        label = { Text("设置") }
                    )
                }
            }
        }
    ) { innerPadding ->
        AnimatedContent(
            targetState = Triple(currentVideo, currentCourseId, selectedTab),
            transitionSpec = {
                // 检查是否是纯粹的底部导航栏tab切换
                val isTabSwitch = initialState.third != targetState.third && 
                    initialState.first == null && initialState.second == null &&
                    targetState.first == null && targetState.second == null

                if (isTabSwitch) {
                    // Tab切换时不显示动画
                    fadeIn() togetherWith fadeOut()
                } else {
                    // 其他情况(课程详情、视频播放、设置页面切换)保持原有动画
                    if (isNavigatingForward) {
                        (slideInHorizontally { width -> width } + fadeIn()) togetherWith 
                        (slideOutHorizontally { width -> -width } + fadeOut())
                    } else {
                        (slideInHorizontally { width -> -width } + fadeIn()) togetherWith 
                        (slideOutHorizontally { width -> width } + fadeOut())
                    }
                }
            },
            modifier = Modifier.padding(innerPadding)
        ) { (video, courseId, tab) ->
            when {
                video != null -> {
                    VideoPlayerScreen(
                        videoUrl = video.url,
                        videoTitle = video.title,
                        onBackClick = { 
                            isNavigatingForward = false
                            currentVideo = null 
                        },
                        modifier = Modifier
                    )
                }
                courseId != null -> {
                    CourseDetailScreen(
                        courseId = courseId,
                        onBackClick = { 
                            isNavigatingForward = false
                            currentCourseId = null 
                        },
                        onVideoClick = { video -> 
                            isNavigatingForward = true
                            currentVideo = video 
                        },
                        modifier = Modifier
                    )
                }
                tab == 0 -> {
                    CoursesScreen(
                        modifier = Modifier,
                        onCourseClick = { courseId -> 
                            isNavigatingForward = true
                            currentCourseId = courseId 
                        }
                    )
                }
                tab == 1 -> {
                    // 将设置页面的内容包装在一个新的 AnimatedContent 中
                    AnimatedContent(
                        targetState = currentSettingsScreen,
                        transitionSpec = {
                            if (isNavigatingForward) {
                                (slideInHorizontally { width -> width } + fadeIn()) togetherWith 
                                (slideOutHorizontally { width -> -width } + fadeOut())
                            } else {
                                (slideInHorizontally { width -> -width } + fadeIn()) togetherWith 
                                (slideOutHorizontally { width -> width } + fadeOut())
                            }
                        }
                    ) { settingsScreen ->
                        when (settingsScreen) {
                            "cardManagement" -> CardManagementScreen(
                                modifier = Modifier,
                                onBackClick = { 
                                    isNavigatingForward = false
                                    currentSettingsScreen = null 
                                },
                                backIcon = { Icon(painter = painterResource(id = R.drawable.ic_back), contentDescription = "返回") }
                            )
                            else -> SettingsScreen(
                                modifier = Modifier,
                                onCardManagementClick = { 
                                    isNavigatingForward = true
                                    currentSettingsScreen = "cardManagement" 
                                },
                                cardManagementIcon = { Icon(painter = painterResource(id = R.drawable.ic_card_management), contentDescription = "卡密管理") }
                            )
                        }
                    }
                }
            }
        }
    }
}
